/**
 * Copyright (c) 2019-2021,  陈俊兵 (cjb6b.com@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ktjiaoyu.advance.threadlocal;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 *
 * @packageName com.ktjiaoyu.advance.threadlocal
 * @fileName ShiroTest.java
 * @author 陈俊兵 (cjb6b.com@gmail.com)
 * @createTime 2023/7/27 15:27
 * @lastModify 2023/7/27 15:27
 * @version 1.0.0
 */
public class ShiroThreadLocalTest {


    public static void main(String[] args) {
        // 记载ini配置文件
        Realm realm = new IniRealm("classpath:shiro.ini");
        // 获取安全管理器对象
        DefaultSecurityManager manager = new DefaultSecurityManager();
        // 设置安全数据源
        manager.setRealm(realm);
        // 设置管理器
        SecurityUtils.setSecurityManager(manager);

//        Subject subject = SecurityUtils.getSubject();

        Thread requestThread1 = new Thread(()->{
            // 第一个请求用户
            Subject user1 = SecurityUtils.getSubject();
            // 再获取一次
            Subject user2 = SecurityUtils.getSubject();
            System.out.println(Thread.currentThread().getName() + "获得用户第1次：" + user1);
            System.out.println(Thread.currentThread().getName() + "获得用户第2次：" + user2);
        });
        requestThread1.start();

        Thread requestThread2 = new Thread(()->{
            // 获取subject对象（用户）
            Subject user1 = SecurityUtils.getSubject();
            Subject user2 = SecurityUtils.getSubject();
            System.out.println(Thread.currentThread().getName() + "获得用户第1次：" + user1);
            System.out.println(Thread.currentThread().getName() + "获得用户第2次：" + user2);
        });

        requestThread2.start();

//        // 创建登录的信息
//        UsernamePasswordToken token = new UsernamePasswordToken("root", "root");
//        // 查看用户是否登录
//        System.out.println("用户是否登录：" + subject.isAuthenticated());
//        // 尝试登录
//        try {
//            subject.login(token);
//            System.out.println("用户是否登录：" + subject.isAuthenticated());
//        } catch (AuthenticationException e) {
//            e.printStackTrace();
//            System.out.println("用户名或密码错误，登录失败");
//        }

    }

}
